package collector.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class Configuration {

    private static final Properties p = new Properties();
    public static final List<String> types = new ArrayList<String>();
    public static final Map<String, List<String>> pages = new HashMap<String, List<String>>();
    public static final Map<String, String> clazz = new HashMap<String, String>();

    static {
        loadProperties(Constants.PROPERTIES_FILE);
        loadData();
    }

    public static boolean loadProperties(String path) {
        boolean flag = false;
        Properties properties = p;
        InputStream is = null;
        try {
            is = Configuration.class.getResourceAsStream("/" + path);
            properties.load(is);
            flag = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            CloseUtil.closeInputStream(is);
        }
        return flag;
    }
    
    public static void loadData() {
        String _types = p.getProperty(Constants.COLLECTOR_TYPES);
        if (null != _types) {
            for (String type : _types.split(",,")) {
                types.add(type);
                
                String _clazz = p.getProperty(type + ".class");
                if (null != _clazz) {
                    clazz.put(type, _clazz);
                }
                
                List<String> pageList = new ArrayList<String>();
                String _pages = p.getProperty(type + ".pages");
                if (null != _pages) {
                    for (String page : _pages.split(",,")) {
                        pageList.add(page);
                    }
                    pages.put(type, pageList);
                }
                pageList = null;
            }
        }
    }

    public static String getProperty(String name) {
        return p.getProperty(name);
    }
    
    public static String getProperty(String name, String defaultValue) {
        String s = p.getProperty(name);
        if (null == s) {
            s = defaultValue;
        }
        return s;
    }
    
    public static List<String> getAllPages() {
        List<String> l = new ArrayList<String>();
        for (String type : Configuration.types) {
            for (String url : Configuration.pages.get(type)) {
                l.add(url);
            }
        }
        return l;
    }

    public static void main(String[] args){
        System.out.println(Configuration.getProperty("log4j.rootLogger", ""));
        System.out.println(Configuration.getProperty("system.id", ""));
    }
}
